package study.线程池.forkJoin;

import study.User;

import java.util.List;
import java.util.concurrent.RecursiveTask;

/**
 * @Author 刘伟涛
 * @Date 2023/12/5 17:00
 **/
public class SimpleTask extends RecursiveTask<String> {
    static final int THRESHOLD = 2;
    List<User> userList;
    int start;
    int end;

    public SimpleTask(List<User> userList, int start, int end) {
        this.userList = userList;
        this.start = start;
        this.end = end;
    }
    @Override
    protected String compute() {
        if(end - start <= THRESHOLD){
            StringBuilder stringBuilder = new StringBuilder();
            for(int i = start; i < end; i++){
                stringBuilder.append(userList.get(i).getName());
                try {
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return stringBuilder.toString();
        }
        //拆分操作
        int middle = (end + start) / 2;
        System.out.println(String.format("split %d~%d ==> %d~%d, %d~%d", start, end, start, middle, middle, end));
        SimpleTask simpleTask1 = new SimpleTask(userList, start, middle);
        SimpleTask simpleTask2 = new SimpleTask(userList, middle, end);
        //执行子线程任务
        invokeAll(simpleTask1,simpleTask2);

        //获取子线程结果
        String join1 = simpleTask1.join();
        String join2 = simpleTask2.join();
        String result = join1 + join2;
        System.out.println("result = " + join1 + " + " + join2 + " ==> " + result);
        return join1 + join2;
    }
}
